<template>
  <div class="page-account">
    <div class="page-account-container">
      <div class="page-account-top">
        <div class="page-account-top-logo">
          <img src="@/assets/images/logo.png" alt="logo" />
        </div>
        <div class="page-account-top-desc">灯塔系统</div>
      </div>
      <Login @on-submit="handleSubmit">
        <UserName name="username" :value="username"></UserName>
        <Password name="password" :value="password" enter-to-submit></Password>
        <div class="page-account-auto-login">
          <Checkbox v-model="autoLogin" size="large">{{
            $t("page.login.remembers")
          }}</Checkbox>
          <a @click="modify">{{ $t("page.login.forgot") }}</a>
        </div>
        <Submit :loading="submitloading" class="submitLogin">{{
          $t("page.login.submit")
        }}</Submit>
      </Login>
      <!-- <div class="page-account-other">
        <span>{{ $t("page.login.other") }}</span>
        <img
          @click="handleDingLogin"
          src="@/assets/svg/icon-social-dingding.svg"
          alt="dingding"
        />
      </div> -->
    </div>
    <!-- <i-copyright /> -->
    <ding-code ref="dingModal"></ding-code>
  </div>
</template>
<script>
// import iCopyright from "@/components/copyright";
import { mapActions, mapGetters } from "vuex";
import mixins from "../mixins";
import DingCode from "@/components/ding/dingCode";
import Setting from "@/setting";
import base64 from "../../../libs/base64.js";
// import { createWebSocket } from '../../../plugins/request/websocket';
import util from "@/libs/util";
export default {
  mixins: [mixins],
  components: { DingCode },
  data() {
    return {
      submitloading: false,
      autoLogin: true,
      luck: true,
      username: "",
      password: "",
      baseUrl: Setting.apiBaseURL,
    };
  },
  computed: {
    ...mapGetters({
      loginInfo: "loginInfo",
    }),
  },
  mounted() {
    if (this.getQueryVariable("userid")) {
      this.submitloading = true;
      this.logins({ user_id: this.getQueryVariable("userid") })
        .then((res) => {
          // this.storage.set('userInfo', res.info);
          if (+res.info.is_defalut_password === 1) {
            this.$router.replace({ name: "register", query: { type: 2 } });
          } else {
            this.getmenu(res.info.project_id).then(() => {
              this.closeAll();
              this.submitloading = false;
              // 重定向对象不存在则返回顶层路径
              // createWebSocket();
              this.$router.replace(this.$route.query.redirect || "/");
            });
          }
          //
          // this.getmenu(res.info.project_id).then(() => {
          //     this.closeAll();
          //     this.submitloading = false
          //     // 重定向对象不存在则返回顶层路径
          //     createWebSocket()
          //     this.$router.replace(this.$route.query.redirect || '/');
          // });
          // this.$router.replace(this.$route.query.redirect || '/');
        })
        .catch(() => {
          this.submitloading = false;
          this.luck = true;
        })
        .finally(() => {
          window.setTimeout(() => {
            this.submitloading = false;
            this.luck = true;
          }, 2000);
        });
    }
    if (this.$route.query.code && this.$route.query.code !== "") {
      this.submitloading = true;
      this.dingLogin({
        code: this.$route.query.code,
      })
        .then((res) => {
          this.getmenu().then(() => {
            this.closeAll();
            this.submitloading = false;
            // 重定向对象不存在则返回顶层路径
            // createWebSocket();
            this.$router.replace(this.$route.query.redirect || "/");
          });
        })
        .catch(() => {
          this.submitloading = false;
          this.luck = true;
        })
        .finally(() => {
          window.setTimeout(() => {
            this.submitloading = false;
            this.luck = true;
          }, 2000);
        });
    }
  },
  beforeMount() {
    // if (window.localStorage.getItem('loginInfo')) {
    //     let obj = JSON.parse(window.localStorage.getItem('loginInfo'));
    //     this.username = obj.username;
    //     this.password = obj.password;
    // }
    if (util.cookies.get("username") && util.cookies.get("password")) {
      let username = util.cookies.get("username");
      this.username = username;
      let password = util.cookies.get("password");
      // let enc = window.btoa(password) //编码成base64的
      let dec = window.atob(password); // 把base64解码
      this.password = dec;
    }
  },
  methods: {
    ...mapActions("admin/page", ["closeAll"]),
    ...mapActions("admin/account", [
      "login",
      "logins",
      "getmenu",
      "dingLogin",
      "SetLoginInfo",
    ]),
    modify() {
      this.$router.replace({ name: "register", query: { type: 1 } });
    },
    /**
     * @description 登录
     * 表单校验已有 iView Pro 自动完成，如有需要修改，请阅读 iView Pro 文档
     */
    handleSubmit(valid, values) {
      if (valid) {
        const { username, password } = values;

        if (this.luck) {
          this.luck = false;
          this.submitloading = true;
          this.login({
            username,
            password,
          })
            .then((res) => {
              this.storage.set("userInfo", res.info);
              // let msg = {
              //     'Id': 1010,
              //     'AccessToken': '',
              //     'MsgType': 'DeviceAuthReq',
              //     'Content': {
              //         'AuthType': 2,
              //         'Credential': base64.b64EncodeUnicode(username + ':' + password)
              //     }
              // }
              // this.$websocket.sendSock(msg)
              if (this.autoLogin) {
                // let userLogin = {
                //     username: values.username,
                //     password: values.password
                // };
                // window.localStorage.setItem(
                //     'loginInfo',
                //     JSON.stringify(userLogin)
                // );
                let enc = window.btoa(password);
                util.cookies.set("username", username);
                util.cookies.set("password", enc);
              } else {
                if (
                  util.cookies.get("username") &&
                  util.cookies.get("password")
                ) {
                  util.cookies.remove("username");
                  util.cookies.remove("password");
                }
                // if (window.localStorage.getItem('loginInfo')) {
                //     window.localStorage.removeItem('loginInfo');
                // }
              }
              if (+res.info.is_defalut_password === 1) {
                this.$router.replace({ name: "register", query: { type: 2 } });
              } else {
                this.getmenu(res.info.project_id).then(() => {
                  if (
                    this.$route.query.redirect &&
                    this.$route.query.redirect.indexOf("/clueform") > -1
                  ) {
                    window.location.href = this.$route.query.redirect;
                    return;
                  }
                  this.closeAll();
                  this.submitloading = false;
                  // 重定向对象不存在则返回顶层路径
                  // createWebSocket();
                  if (
                    this.$route.query.redirect &&
                    this.$route.query.redirect === "monthReport"
                  ) {
                    if (this.baseUrl === "https://beacon.api.jgyljt.com") {
                      window.location.href =
                        "https://beacon.jgyljt.com/monthReport";
                    } else {
                      console.log("null");
                    }
                    if (this.baseUrl === "http://dengta-test.api.jgyljt.com") {
                      window.location.href =
                        "http://dengta-test.jgyljt.com/monthReport";
                    }
                  } else {
                    this.$router.replace(this.$route.query.redirect || "/");
                  }
                });
              }
            })
            .catch(() => {
              this.submitloading = false;
              this.luck = true;
            })
            .finally(() => {
              window.setTimeout(() => {
                this.submitloading = false;
                this.luck = true;
              }, 2000);
            });
        }
      }
    },

    // 钉钉登录
    handleDingLogin() {
      this.$refs.dingModal.show("/login");
    },
    getQueryVariable(variable) {
      let url = decodeURIComponent(window.location.href);
      let index = url.indexOf(variable);
      let query = url.substring(index);
      let vars = query.split("&");
      for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return false;
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ivu-input-prefix,
.ivu-input-suffix {
  display: none;
}
.page-account-auto-login label {
  font-size: 16px !important;
}

/deep/.submitLogin button {
  color: #fff;
  // background-color: #30b862;
  // border-color: #30b862;
  height: 40px;
  padding: 0 15px;
  font-size: 16px;
  border-radius: 4px;
}

/deep/.submitLogin button span {
  font-size: 16px !important;
}
</style>
